package com.bnz.listener;

import com.bnz.pojo.Dessert;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.HashMap;
import java.util.Map;

@WebListener
public class MyServletContextListener implements ServletContextListener, ServletContextAttributeListener {

    //1. application组件被创建
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //1.1 定义一组商品
        Dessert p1 = new Dessert("1001","芒果雪梅娘",12,100);
        Dessert p2 = new Dessert("1002","玛格丽特小饼",6,20);
        Dessert p3 = new Dessert("1003","栗子布丁",8,10);
        Dessert p4 = new Dessert("1004","提速米拉",16,60);
        Dessert p5 = new Dessert("1005","莫斯蛋糕",18,30);
        Dessert p6 = new Dessert("1006","巧克力摩斯",20,18);
        Dessert p7 = new Dessert("1007","水果卡士达",25,25);
        Dessert p8 = new Dessert("1008","椰香奶冻糕",13,6);
        Dessert p9 = new Dessert("1009","芒果西米露",12,17);
        Dessert p10 = new Dessert("1010","桔红李子冻",9,31);

        //1.2 放到一个Map中
        Map<String,Dessert> dessertMap = new HashMap<>();
        dessertMap.put(p1.getDid(),p1);
        dessertMap.put(p2.getDid(),p2);
        dessertMap.put(p3.getDid(),p3);
        dessertMap.put(p4.getDid(),p4);
        dessertMap.put(p5.getDid(),p5);
        dessertMap.put(p6.getDid(),p6);
        dessertMap.put(p7.getDid(),p7);
        dessertMap.put(p8.getDid(),p8);
        dessertMap.put(p9.getDid(),p9);
        dessertMap.put(p10.getDid(),p10);

        //1.3 将集合放到上下文环境中
        sce.getServletContext().setAttribute("desserts",dessertMap);

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("application被销毁。。。");
    }

   //2. application组件属性值改变监听
    @Override
    public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {

    }


}
